import React, { useEffect } from "react";
import {
  Cells, ListView, ListViewArea
} from '@wecode/react-weui';
import PullToRefresh from '@wecode/pulltorefresh-react';

import image01 from './images/1.jpg';
import image04 from './images/2.jpg';
import image03 from './images/3.jpg';

export default function Refresh() {
 
  function onScrollHandle(event) {
    const clientHeight = event.target.clientHeight;
    const scrollHeight = event.target.scrollHeight;
    const scrollTop = event.target.scrollTop;
    const isBottom = (clientHeight + scrollTop === scrollHeight);
    if (isBottom) {
      // console.log('滚动到最底部事件')
    }    
  }
  useEffect(() => {
    HWH5.navTitle({ title: "下拉刷新示例" });

    const refreshDemo = document.getElementById('refresh-demo');

    refreshDemo.addEventListener('scroll', onScrollHandle);

    const storageKey = 'refresh-demo-scrollTop';
    // 获取缓存，判断是否有记住上次的位置
    HWH5.getStorage(storageKey)
      .then(data => { 
        if (data === 'undefined'|| !data) { return; }
        const lastScrollData = typeof data === 'string' ? JSON.parse(data) : data;
        if (lastScrollData && lastScrollData.scrollTop) {
          // 滚动到历史浏览的位置
          refreshDemo.scrollTop = lastScrollData.scrollTop;
        }
      });
    return () => {
      // 组件销毁时，记住上次滚动的位置
      const lastScrollTop =  refreshDemo.scrollTop;
      HWH5.setStorage({
        key: storageKey,
        data: JSON.stringify({ scrollTop: lastScrollTop })
      });
      // 销毁滚动事件
      refreshDemo.removeEventListener('scroll', onScrollHandle);
    }
  });
  return (<PullToRefresh
    mainElement="refresh-demo" // 设置滚动id
    style={{ height: '100vh', overflow: 'scroll' }} // 设置滚动区域样式
    onRefresh={async () => { // 模拟异步请求，返回 promise
      await new Promise(resolve => {
        setTimeout(() => {
          resolve();
        }, 1000);
      });
      HWH5.showToast({ msg: '刷新回调事件', type: 'n' });
    }}
  >
    <Cells style={{ marginTop: 0 }}>
      {[...Array(10)].map((item, index) => {
        return (
          <React.Fragment key={index}>
            <ListView
              src={image01}
              title="AI系列培训-Introduction to AI & ML-分布式与并行与交流，分布式与并行与交流,分布式与并行与交流，分布式与并行与交流,分布式与并行与交流，分布式与并行与交流"
              footer={(
                <span>
                  <i className="icon-16 icon-16-comment" />
                  1235评论
                </span>
              )}
            />
            <ListViewArea>
              <ListView
                src={image04}
                title="AI系列培训-Introduction to AI & ML-分布式与并行与交流，分布式与并行与交流,分布式与并行与交流，分布式与并行与交流,分布式与并行与交流，分布式与并行与交流"
                footer="1235播放"
              />
              <ListView src={image03} title="AI系列培训" footer="1235播放" />
            </ListViewArea>
          </React.Fragment>)
      })}
    </Cells>

  </PullToRefresh>)
}
